package intelligentcity.memoirs;

import intelligentcity.conf.Conf;

import java.util.LinkedList;

public class Diary extends Thread {

    private int entryNorth;
    private int entrySouth;
    private int entryEast;
    private int entryWest;

    private LinkedList<Page> pages;

    private int entryNorthOnCurrentPage;
    private int entrySouthOnCurrentPage;
    private int entryEastOnCurrentPage;
    private int entryWestOnCurrentPage;

    public Diary() {
        pages = new LinkedList<>();
    }

    @Override
    public void run() {
        while (true) {
            Conf.stop(Conf.timeOfWritingOnOnePage);
            updatePages();
        }
    }

    public synchronized void updatePages() {
        if (pages.size() == Conf.maxNumberOfPages) {
            entryNorth -= pages.getFirst().getEntryNorth();
            entrySouth -= pages.getFirst().getEntrySouth();
            entryEast -= pages.getFirst().getEntryEast();
            entryWest -= pages.getFirst().getEntryWest();
            pages.remove();
        }

        pages.add(new Page(entryNorthOnCurrentPage, entrySouthOnCurrentPage, entryEastOnCurrentPage,
                entryWestOnCurrentPage));

        entryNorth += entryNorthOnCurrentPage;
        entrySouth += entrySouthOnCurrentPage;
        entryEast += entryEastOnCurrentPage;
        entryWest += entryWestOnCurrentPage;

        // log();

        entryNorthOnCurrentPage = 0;
        entrySouthOnCurrentPage = 0;
        entryEastOnCurrentPage = 0;
        entryWestOnCurrentPage = 0;
    }

    public synchronized void incEntryNorthOnCurrentPage() {
        this.entryNorthOnCurrentPage++;
    }

    public synchronized void incEntrySouthOnCurrentPage() {
        this.entrySouthOnCurrentPage++;
    }

    public synchronized void incEntryEastOnCurrentPage() {
        this.entryEastOnCurrentPage++;
    }

    public synchronized void incEntryWestOnCurrentPage() {
        this.entryWestOnCurrentPage++;
    }

    public synchronized int getEntryNorth() {
        return entryNorth;
    }

    public synchronized int getEntrySouth() {
        return entrySouth;
    }

    public synchronized int getEntryEast() {
        return entryEast;
    }

    public synchronized int getEntryWest() {
        return entryWest;
    }

    public void log() {
        if (Conf.diaryLogger) {
            System.out.println(toString());
        }
    }

    @Override
    public String toString() {
        return "Diary [entryNorth=" + entryNorth + ", entrySouth=" + entrySouth + ", entryEast=" + entryEast
                + ", entryWest=" + entryWest + ", entryNorthOnCurrentPage=" + entryNorthOnCurrentPage
                + ", entrySouthOnCurrentPage=" + entrySouthOnCurrentPage + ", entryEastOnCurrentPage="
                + entryEastOnCurrentPage + ", entryWestOnCurrentPage=" + entryWestOnCurrentPage + "]";
    }
}
